// pages//chat/chat.js     
var app = getApp();
const websocket = require('../../utils/websocket.js')
Page({
  
  /**
   * 页面的初始数据 as 
   */    
  data: {
    emojiChar: "☺-😋-😌-😍-😏-😜-😝-😞-😔-😪-😭-😁-😂-😃-😅-😆-👿-😒-😓-😔-😏-😖-😘-😚-😒-😡-😢-😣-😤-😢-😨-😳-😵-😷-😸-😻-😼-😽-😾-😿-🙊-🙋-🙏-✈-🚇-🚃-🚌-🍄-🍅-🍆-🍇-🍈-🍉-🍑-🍒-🍓-🐔-🐶-🐷-👦-👧-👱-👩-👰-👨-👲-👳-💃-💄-💅-💆-💇-🌹-💑-💓-💘-🚲",
    //0x1f---
    emoji: [
      "60a", "60b", "60c", "60d", "60f",
      "61b", "61d", "61e", "61f",
      "62a", "62c", "62e",
      "602", "603", "605", "606", "608",
      "612", "613", "614", "615", "616", "618", "619", "620", "621", "623", "624", "625", "627", "629", "633", "635", "637",
      "63a", "63b", "63c", "63d", "63e", "63f",
      "64a", "64b", "64f", "681",
      "68a", "68b", "68c",
      "344", "345", "346", "347", "348", "349", "351", "352", "353",
      "414", "415", "416",
      "466", "467", "468", "469", "470", "471", "472", "473",
      "483", "484", "485", "486", "487", "490", "491", "493", "498", "6b4"
    ],
    emojis: [],//qq、微信原始表情
    emojiShow:false,
    current: 0,
    serverImg: '../../images/man.png',
    userImg:'../../images/man.png',
    ipt_text: '',
    height: 5,
  },
  // 清空输入框
  clearInput: function () {
    this.setData({
      ipt_text: "" 
    })
  },
  // 输入框输入消息赋值
  msginput: function (e) {
    this.setData({
      ipt_text: e.detail.value
    })
  },
  // 发送消息
  sendmsg: function (e) {
    var that = this;
    var content = e.content ? '你好，我想要了解一下《'+e.content+'》这款产品。' : this.data.ipt_text
    var chat_list = this.data.chat_list || [] ;
    if (!content) return wx.showToast({
      title: "内容不能为空",
      icon: "none"
    }), !1;
    var t = {
      sendid: that.data.user.user_id,
      toid: that.data.detail.user_id,
      content: content,
      is_server: false,
      contentType: e.filename ? 'image' : 'text',
      filename: e.filename || '',
      enterprise_id: app.siteInfo.enterprise_id
    }
    var chat_list = that.data.chat_list || []
    chat_list.push(t)
    that.setData({
      ipt_text: '',
      chat_list: chat_list,
    })
    that.scrollTop();
    websocket.send(JSON.stringify(t));
  },
  scrollTop: function () {
    var that = this;
    var chat_list = that.data.chat_list;
    if (chat_list) {
      var chat_listLen = chat_list.length;
    } else {
      var chat_listLen = 1;
    }

    var scrolltop = chat_listLen * 300;
    that.setData({
      scrolltop: scrolltop,
    })
  },


  //文本域失去焦点时 事件处理
  textAreaBlur: function (e) {
    var that = this;
    //获取此时文本域值
    if (this.data.emojiShow){
      var height=200
    }else{
      var height=0
    }
    this.setData({
      ipt_text: that.data.ipt_text,
      height: height,
    })
  },
  //文本域获得焦点事件处理
  textAreaFocus: function (e) {
    var that = this;
    console.log(e)
    let heightVal = e.detail.height ? e.detail.height : 0;
    if (that.data.emojiShow){
      that.setData({
        emojiShow: false,
        height: 5,
      })
      // setTimeout(function () {
      //   that.textAreaFocus();
      // }, 100)
    }else{
      let height = 0;
      let height_02 = 0;
      wx.getSystemInfo({
        success: function (res) {
          height_02 = res.windowHeight;
        }
      })
      height = heightVal - height_02;
      that.setData({
        height: e.detail.value ? 205 : 5,
      })
    }
    
  },
  //点击表情显示隐藏表情盒子
  emojiShowHide: function () {
    var emojiShow = !this.data.emojiShow;
    if (emojiShow){
      var height=200
    }else{
      var height = 0
    }
    this.setData({
      emojiShow: emojiShow,
      height: height,
    })
  },
  //解决滑动穿透问题
  emojiScroll: function (e) {
  },
  //表情选择
  emojiChoose: function (e) {
    var that = this;
    //当前输入内容和表情合并
    if (that.data.ipt_text && that.data.ipt_text != undefined){
      var content = that.data.ipt_text + e.currentTarget.dataset.emoji
    }else{
      var content = e.currentTarget.dataset.emoji
    }
    that.setData({
      ipt_text: content
    })
  },
  previewImg:function(e){
    var that = this;
    var imgSrc = e.currentTarget.dataset.src;
    var url=[];
    url[0] = imgSrc;
    wx.previewImage({
      current:imgSrc,
      urls: url,
    })
  },
 
  onLoad: function (options) {
    var that = this;
    if(options.content){
      that.setData({
        options: options
      })
    }
    app.httpRequest('user/chatRecord', {}, 'get', false, function(res){
      that.setData({
        chat_list: res.data.list.data
      })
      that.scrollTop();
    })
    wx.onSocketMessage((result) => {
      console.log(result)
      var list = that.data.chat_list || [];
      var msg = JSON.parse(result.data);
      if (msg){
        list.push(msg)
        that.setData({
          chat_list: list
        })
      }
    })

    var em = {} , emChar = that.data.emojiChar.split("-");
    var emojis = []
    that.data.emoji.forEach(function (v, i) {
      em = {
        char: emChar[i],
        emoji: "0x1f" + v
      };
      emojis.push(em)
    });
    that.setData({
      emojis: emojis
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.scrollTop();
    var that = this;
    app.httpRequest('card.card/detail', {}, 'get', false, function(res){
      that.setData({
        enterprise: res.data.enterprise,
        detail: res.data.detail,
        pageShow: true,
        user: wx.getStorageSync('userInfo'),
        serverImg: res.data.detail.avatar_url,
        userImg: wx.getStorageSync('userInfo').avatarUrl
      })
      if(that.data.options){
        that.sendmsg(that.data.options);
      } 
      wx.setNavigationBarTitle({
        title: res.data.detail.real_name,
      })
    })
  },
  // 复制信息
  copyText:function(e){
    var that = this;
    var copyText = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: copyText,
      success(res) {
        wx.getClipboardData({
          success(res) {
          }
        })
      }
    })
    app.userBehavior(104,'复制了你的信息：' + copyText)
  },
  // 打电话 
  makePhoneCall: function (e) {
    var that = this;
    app.userBehavior(102,'拨打了你的电话')
    wx.makePhoneCall({
      phoneNumber: that.data.detail.mobile,
    })
  },
  // 打开位置
  openLocation:function(){
    var that = this;
    var latitude = parseFloat(that.data.enterprise.latitude);
    var longitude = parseFloat(that.data.enterprise.longitude);
    app.userBehavior(103,'查看了公司地址')
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      name:that.data.enterprise.name,
      address:that.data.enterprise.detail,
      scale: 14,
    })
  },
  getPhoneNumber: function (e) {
    var that = this;
    var iv = encodeURIComponent(e.detail.iv)
    var type = e.currentTarget.dataset.type || '';
    var encryptedData = encodeURIComponent(e.detail.encryptedData)
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      
    } else {
      wx.request({
        url: app.siteInfo.siteroot + 'user/getPhone',
        method: "post",
        data: {
          iv: iv,
          encryptedData: encryptedData,
          token: wx.getStorageSync('token'),
          enterprise_id: app.siteInfo.enterprise_id,
        },
        success: function (res) {
          if(res.data.code == -1){
            wx.navigateTo({
              url: '/pages/welcome/welcome',
            })
            return;
          }
          if(res.data.code == 1){
            var user = wx.getStorageSync('userInfo');
            user.phone = res.data.data.phone;
            wx.setStorageSync('userInfo', user)
            that.setData({
              user: user,
            })
            that.linkMe()
          }
        }
      })
    }
  },
  linkMe:function(){
    app.userBehavior(128,'用户请求电话联系')
    wx.showModal({
      content: '手机号已发送，请注意来电',
      showCancel: false
    })
  },
  onHide: function () {
    var that = this;
    
  },
  onUnload: function () {
    wx.closeSocket();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  //上传图片
  uploadImage: function () {
    var that = this;

    wx.chooseImage({
      count: 1,  //最多可以选择的图片总数
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        //启动上传等待中...
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 10000
        })

        wx.uploadFile({
          url: app.siteInfo.siteroot+'upload/uploadfile',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
          },
          header: {
            "Content-Type": "multipart/form-data"
          },
          success: function (res) {
            wx.hideToast();
            var data = JSON.parse(res.data);
            
            if(data.code==200){
              var chat_list = that.data.chat_list || []
              var t = {
                sendid: 1,
                toid: 2,
                content: data.filesrc,
                isServer: false,
                contentType: 'image',
              }
              
              chat_list.push(t)
              that.setData({
                chat_list: chat_list || []
              })
              that.scrollTop();
              websocket.send(JSON.stringify(t));
            }
          },
          fail: function (res) {
            wx.hideToast();
            wx.showModal({
              title: '错误提示',
              content: '上传图片失败',
              showCancel: false,
              success: function (res) { }
            })
          }
        });
      }
    });
  },
})